﻿using BySoft.Server.Business;
using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.StockManage
{
    public partial class RquisitionEdit : AuthBasePage
    {
        #region 属性定义
        private string m_strTbl = "BS_Rquisition";
        private string m_strMainKey = "BillID";

        private DataTable DtRquisitionData
        {
            get
            {
                if (null == Session["RquisitionData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["RquisitionData"];
                }
            }
            set
            {
                Session["RquisitionData"] = value;
            }
        }

        private DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BillDetailID");//0
            dt.Columns.Add("OrderNum");//1
            dt.Columns.Add("MaterialRequirementDetailID");//2
            dt.Columns.Add("MaterialRequirementID");//2
            dt.Columns.Add("WorkOrderNo");//3
            dt.Columns.Add("MaterialID");//4
            dt.Columns.Add("MaterialName");//5
            dt.Columns.Add("Specifications");//6
            dt.Columns.Add("Unit");//7
            dt.Columns.Add("AdviseNum");//8
            dt.Columns.Add("ResNum");//8
            dt.Columns.Add("Nums");//9
            dt.Columns.Add("MMNumber");
            dt.Columns.Add("SingleMMNumber");//11
            dt.Columns.Add("IsNew");//11
            dt.Columns.Add("IsDel");//11
            return dt;
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
            DtRquisitionData = null;
            string id = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id"));
            if(!string.IsNullOrEmpty(id))
            {
                DataTable dt = BsRquisitionBusiness.GetDataByBillID(id);
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow drow=dt.Rows[0];
                    this.lblBillID.Text = id;
                    this.cpBillDate.Value = string.Format("{0:yyyy-MM-dd}", drow["BillDate"]);
                    DataTable dtemp=DtRquisitionData.Copy();
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow d = dtemp.NewRow();
                        d["BillDetailID"] = CommonMethod.GetString(dr["BillDetailID"]);
                        d["OrderNum"] = CommonMethod.GetString(dr["OrderNum"]);
                        d["MaterialRequirementDetailID"] = CommonMethod.GetString(dr["MaterialRequirementDetailID"]);
                        d["MaterialRequirementID"] = CommonMethod.GetString(dr["MaterialRequirementID"]);
                        d["WorkOrderNo"] = CommonMethod.GetString(dr["WorkOrderNo"]);
                        d["MaterialID"] = CommonMethod.GetString(dr["MaterialID"]);
                        d["MaterialName"] = CommonMethod.GetString(dr["MaterialName"]);
                        d["Specifications"] = CommonMethod.GetString(dr["Specifications"]);
                        d["Unit"] = CommonMethod.GetString(dr["Unit"]);
                        d["AdviseNum"] = CommonMethod.GetString(dr["AdviseNum"]);
                        d["ResNum"] = CommonMethod.GetString(dr["ResNum"]);
                        d["Nums"] = CommonMethod.GetString(dr["Nums"]);
                        d["MMNumber"] = CommonMethod.GetString(dr["MMNumber"]);
                        d["SingleMMNumber"] = CommonMethod.GetString(dr["SingleMMNumber"]);
                        d["IsNew"] = "-1";
                        d["IsDel"] = "-1";
                        dtemp.Rows.Add(d);
                    }
                    dtemp.AcceptChanges();
                    DtRquisitionData = dtemp.Copy();
                }
            }
            BindData();
        }
        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }
        private void AddPro()
        {
            DtRquisitionData = GetAddPro(DtRquisitionData).Copy();
        }
        private DataTable GetAddPro(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblBillDetailID = gvr.FindControl("lblBillDetailID") as Label;
                Label lblMaterialRequirementDetailID = gvr.FindControl("lblMaterialRequirementDetailID") as Label;
                Label lblMaterialRequirementID = gvr.FindControl("lblMaterialRequirementID") as Label;
                Label lblWorkOrderNo = gvr.FindControl("lblWorkOrderNo") as Label;
                Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                Label lblUnit = gvr.FindControl("lblUnit") as Label;
                Label lblAdviseNum = gvr.FindControl("lblAdviseNum") as Label;
                Label lblResNum = gvr.FindControl("lblResNum") as Label;
                TextBox txtNums = gvr.FindControl("txtNums") as TextBox;
                Label lblSingleMMNumber = gvr.FindControl("lblSingleMMNumber") as Label;
                TextBox txtMMNumber = gvr.FindControl("txtMMNumber") as TextBox;

                string MaterialID = CommonMethod.GetString(lblMaterialID.Text);


                DataRow[] drs = dtTemp.Select("MaterialID='" + MaterialID + "'");
                if (drs.Length > 0)
                {

                    drs[0]["BillDetailID"] = GetGridViewString(lblBillDetailID);
                    drs[0]["MaterialRequirementDetailID"] = GetGridViewString(lblMaterialRequirementDetailID);
                    drs[0]["MaterialRequirementID"] = GetGridViewString(lblMaterialRequirementID);
                    drs[0]["WorkOrderNo"] = GetGridViewString(lblWorkOrderNo);
                    drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                    drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                    drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                    drs[0]["Unit"] = GetGridViewString(lblUnit);
                    drs[0]["AdviseNum"] = GetGridViewString(lblAdviseNum);
                    drs[0]["ResNum"] = GetGridViewString(lblResNum);
                    drs[0]["Nums"] = GetGridViewString(txtNums);
                    drs[0]["SingleMMNumber"] = GetGridViewString(lblSingleMMNumber);
                    drs[0]["MMNumber"] = GetGridViewString(txtMMNumber);
                }
            }
            return dtTemp;
        }

        private void BindData()
        {
            DataView dv = new DataView(DtRquisitionData);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["OrderNum"] = index;
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.UpdatePanel1, "iframeAutoFit();");
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            AddPro();
            UIHelper.RunScript(this.Page, "importNewRow();");
        }

        protected void btnAddh_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }

            BsRquisitionEntity entity = new BsRquisitionEntity();
            entity.BillID = GetString(lblBillID);
            entity.BillDate = GetDateTime(cpBillDate);
            entity.ModifyUserID = CurrentUser.UserID;
            entity.ModifyUserName = CurrentUser.UserName;
            entity.ModifyDate = DateTime.Now;

            #region 前台绑定BsRquisitiondetailEntity  List
            //List<BsRquisitiondetailEntity> lstbody = new List<BsRquisitiondetailEntity>();
            //int index = 1;
            //foreach (GridViewRow gvr in grdResult.Rows)
            //{
            //    Label lblBillDetailID = gvr.FindControl("lblBillDetailID") as Label;
            //    if (lblBillDetailID == null || string.IsNullOrEmpty(lblBillDetailID.Text.Replace("&nbsp;", "")))
            //    {
            //        continue;
            //    }

            //    Label lblOrderNum = gvr.FindControl("lblOrderNum") as Label;
            //    Label lblMaterialRequirementDetailID = gvr.FindControl("lblMaterialRequirementDetailID") as Label;
            //    Label lblWorkOrderNo = gvr.FindControl("lblWorkOrderNo") as Label;
            //    Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
            //    Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
            //    Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
            //    Label lblUnit = gvr.FindControl("lblUnit") as Label;
            //    Label lblAdviseNum = gvr.FindControl("lblAdviseNum") as Label;
            //    TextBox txtNums = gvr.FindControl("txtNums") as TextBox;
            //    Label lblSingleMMNumber = gvr.FindControl("lblSingleMMNumber") as Label;
            //    TextBox txtMMNumber = gvr.FindControl("txtMMNumber") as TextBox;

            //    if (string.IsNullOrEmpty(txtNums.Text.Trim()))
            //    {
            //        UIHelper.AlertMessage(this.UpdatePanel1, string.Format("第{0}行，请输入数量！", index));
            //        return;
            //    }

            //    BsRquisitiondetailEntity entbody = new BsRquisitiondetailEntity();
            //    entbody.BillDetailID = GetInt(lblBillDetailID);
            //    entbody.BillID = GetString(lblBillID);
            //    entbody.OrderNum = GetInt(lblOrderNum);
            //    entbody.MaterialRequirementDetailID = GetDecimal(lblMaterialRequirementDetailID);
            //    entbody.WorkOrderNo = GetString(lblWorkOrderNo);
            //    entbody.MaterialID = GetString(lblMaterialID);
            //    entbody.Nums = GetDecimal(txtNums);
            //    entbody.MMNumber = GetDecimal(txtMMNumber);

            //    lstbody.Add(entbody);
            //    index++;
            //}

            //if (lstbody.Count < 1)
            //{
            //    UIHelper.AlertMessage(this.UpdatePanel1, "请添加明细！");
            //    return;
            //}
            #endregion
            BsRquisitionBusiness.SaveOrUpdate(entity, DtRquisitionData, "Update");
            base.LogAction(BaseEnum.ActionType.Add, entity.BillID, true, null, new EntityBase[] { entity });
            DtRquisitionData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../StockManage/RquisitionList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "del":
                    AddPro();
                    DataTable dt = DtRquisitionData.Copy();
                    DataRow[] dr = dt.Select("MaterialID='" + strCode.Trim() + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    DtRquisitionData = dt.Copy();
                    BindData();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete +

        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion

            }
        }
        #endregion

        #region 本地方法
        private bool ValidateData()
        {
            AddPro();
            if (DtRquisitionData.Rows.Count < 1)
            {
                UIHelper.AlertMessage(this.UpdatePanel1, "请添加明细！");
                return false;
            }
            return true;
        }
        #endregion

        protected void btnMaterialReq_Click(object sender, EventArgs e)
        {
            AddPro();
            UIHelper.RunScript(this.Page, "importNewRow('1');");
        }
    }
}